package com.wenzi.rule.verification.aop;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wenzi.rule.verification.actuator.ExecutorStrategy;
import com.wenzi.rule.verification.annotate.RuleValid;
import com.wenzi.rule.verification.base.BaseForm;
import com.wenzi.rule.verification.exception.RuleValidException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
public class RuleAspect {
    private static final Log LOG = LogFactory.get(RuleAspect.class);
    @Autowired
    private ExecutorStrategy strategy;

    @Pointcut("@annotation(com.wenzi.rule.verification.annotate.RuleValid)")
    public void rule(){}

    @Around("rule()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //拿到执行的方法，判断该方法是否存在指定的注解
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        RuleValid ruleAnnotation = method.getAnnotation(RuleValid.class);
        Object[] args = joinPoint.getArgs();

        try {
            if (args.length > 0){
                 executeRule(ruleAnnotation,args[0]);
            }
            return joinPoint.proceed();
        } catch (RuleValidException e) {
            throw e;
        }
    }

    public void executeRule(RuleValid ruleValid,Object form){
        if(ruleValid == null || !(form instanceof BaseForm)) return;

        LOG.info("configType:{},name:{}--Rule execution begins",ruleValid.configType(),ruleValid.name());
        try {
            strategy.process(ruleValid.configType(),ruleValid.name(),form);
        }catch (Exception e){
            throw e;
        }

    }
}
